<?php

declare(strict_types=1);

namespace App\Library\Task\library\queue\drivers\redis;


use App\Library\Log\Log;

class QueueDBRedis
{

    //定义对象
    private $_redis;
    //存储前缀
    private $_tb_prefix;

    /**
     * 初始化
     */
    public function __construct() {
        if (!extension_loaded('redis')) {
            throw_exception('redis failed to load');
        }
        $this->_redis = new \Redis();
        $config = config('goods.task_drivers_default.redis');
        $this->_redis->connect($config['host'], (int)$config['port']);
        $this->_redis->auth($config['passwd']);
        $this->_redis->select((int)$config['db']);
        $this->_tb_prefix = $config['prefix'] . 'task_queue_';
//        $this->_tb_prefix = 'nc_QUEUE_';
    }

    /**
     * 入列
     * @param unknown $value
     */
    public function push($value, $driver = 'default') {
        try {
            $tbNumArr = $this->getKeyListNumArray($driver);
            return $this->_redis->lPush($this->getKeyPrefix($driver) . $tbNumArr[array_rand($tbNumArr, 1)], $value);
        } catch (\Exception $exception) {
            Log::error($exception);
            return false;
        }
    }

    /**
     * 取得所有的list key(表)
     */
    public function scan( $driver = 'default' ) {
        $list_key = array();
        $tbNumArr = $this->getKeyListNumArray($driver);
        foreach ($tbNumArr as $oneTb) {
            $list_key[] = $this->getKeyPrefix($driver) . $oneTb;
        }
        return $list_key;
    }

    /**
     * 出列
     * @param unknown $key
     */
    public function pop($key, $time) {
        try {
            if ($result = $this->_redis->brPop($key, $time)) {
                return $result[1];
            }
        } catch (\Exception $exception) {
            Log::error($exception);
        }
    }

    /**
     * 清空,暂时无用
     */
    public function clear( $driver = 'default' ) {
        $tbNumArr = config('goods.task_drivers_default.queue_list.' . $driver . '.num');
        foreach ($tbNumArr as $oneTb) {
            //删除对应驱动的存储集合
            return $this->_redis->del( $this->getKeyPrefix($driver) . $oneTb );
        }

        return 0;
        //$this->_redis->flushAll();
    }

    /**
     * 取得所有的list的数组
     */
    private function getKeyListNumArray($driver) {
        return config('goods.task_drivers_default.queue_list.' . $driver . '.num');
    }

    /**
     * 获取key前缀
     * @param $driver
     */
    private function getKeyPrefix($driver) {
//        return $this->_tb_prefix . $driver . '_';
        return $this->_tb_prefix;
    }

}